package com.study.juc;

import java.util.concurrent.TimeUnit;

public interface Lock {
    
    
    void lock() throws InterruptedException;
    
    void unlock();
}

class BooleanLock implements Lock{
    private boolean lock;
    private Thread holderThread;
    @Override
    public void lock() throws InterruptedException {
        synchronized (this){
            while(lock){
                if(holderThread == Thread.currentThread()) break;
                this.wait();
            }
            holderThread = Thread.currentThread();
            lock = true;
        }
    }
    

    @Override
    public void unlock() {
        synchronized (this){
            if(holderThread == Thread.currentThread()){
                lock =false;
                holderThread = null;
                this.notifyAll();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {


        BooleanLock booleanLock = new BooleanLock();
        
        Thread t1 = new Thread(){
            @Override
            public void run() {
                try {
                    booleanLock.lock();
                    while(true){
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println(Thread.currentThread().getName());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    booleanLock.unlock();
                    System.out.println("北大但"+Thread.currentThread().getName());
                }
            }
        };
        t1.start();
        Thread t2 = new Thread(){
            @Override
            public void run() {
                try {
                    booleanLock.lock();
                    while(true){
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println(Thread.currentThread().getName());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    booleanLock.unlock();
                    System.out.println("北大但"+Thread.currentThread().getName());
                }
            }
        };
        t2.start();
        TimeUnit.SECONDS.sleep(5);
        t2.interrupt();
        
        
    }
}
